package com.imcrl.component.ext
{
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.ui.Mouse;
	import flash.ui.MouseCursor;
	
	import starling.display.Image;
	import starling.events.Event;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	import starling.textures.Texture;
	
	
	public class ButtonImage extends Image
	{
		private var mUseHandCursor:Boolean;
		public function ButtonImage(texture:Texture)
		{
			super(texture);
			
			addEventListener(TouchEvent.TOUCH, touchHandle);
		}
		
		public function get useHandCursor():Boolean { return mUseHandCursor; }
		public function set useHandCursor(value:Boolean):void
		{
			if (value == mUseHandCursor) return;
			mUseHandCursor = value;
		}
		
		
		private var mouseIsDown:Boolean=false;
		private function touchHandle(e:TouchEvent):void{
			var touch:Touch = e.getTouch(this);
			if (touch == null) return;
			var m:Point;
			if (touch.phase == TouchPhase.BEGAN && !mouseIsDown)
			{
				mouseIsDown=true;
			}
			else if (touch.phase == TouchPhase.MOVED && mouseIsDown)
			{
				var buttonRect:Rectangle = getBounds(stage);
				if (touch.globalX < buttonRect.x ||
					touch.globalY < buttonRect.y ||
					touch.globalX > buttonRect.x + buttonRect.width ||
					touch.globalY > buttonRect.y + buttonRect.height)
				{
					mouseIsDown = false;
					return;
				}
			}
			else if (touch.phase == TouchPhase.ENDED && mouseIsDown)
			{
				mouseIsDown=false;
				dispatchEvent(new Event(Event.TRIGGERED, true));
			}
			
			if(mUseHandCursor)Mouse.cursor = e.interactsWith(this) ? MouseCursor.BUTTON : MouseCursor.AUTO;
		}
	}
}